package cn.ivicar.cloud.ws;

import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Path("ping")
public class PingResource {
    @Context
    protected ServletContext context;

    @GET
    @Path("online")
    @Produces(MediaType.TEXT_HTML)
    public Response getTest() {
        return Response.ok().build();
    }

    @GET
    @Path("version")
    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
    public Response getVersion() {
        try {
            String relativeWarPath = "/META-INF/MANIFEST.MF";
            InputStream versionStream = this.context.getResourceAsStream(relativeWarPath);
            Properties versionProp;
            if (versionStream != null) {
                versionProp = new Properties();
                try {
                    versionProp.load(versionStream);
                } catch (IOException e) {
                    throw new InternalError(String.format("加载资源的%s文件出错。%s", relativeWarPath,
                        e.getMessage()));
                }
            } else {
                throw new InternalError(String.format("没有发现%s资源文件。", relativeWarPath));
            }

            Map<String, Object> entity = new HashMap<String, Object>();
            String version = versionProp.getProperty("Implementation-Version");
            String buildDate = versionProp.getProperty("Build-Date");
            String scmRevision = versionProp.getProperty("SCM-Revision");
            entity.put("version", version + "-" + buildDate + "-" + scmRevision);

            return Response.ok().entity(entity).build();
        } catch (Exception e) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .type(MediaType.APPLICATION_JSON + ";charset=utf-8").entity(e.getMessage()).build();
        }
    }
}
